package com.qmhl.toolposition.api

import com.qmhl.toolposition.MyApplication
import com.qmhl.toolposition.utils.JSONUtil
import com.qmhl.toolposition.utils.PreferenceUtil
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object NetworkModule {

    fun provideOkHttpClient(): OkHttpClient {


        var currentUser = PreferenceUtil.getCurrentUser()
        var token = currentUser.token

        val okHttpClient = OkHttpClient.Builder()

        val cache = Cache(MyApplication.instant.cacheDir, 1024 * 1024 * 100)
        okHttpClient.cache(cache)

        okHttpClient.connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)

        okHttpClient.addInterceptor(Interceptor {

            val original: Request = it.request()
            val request: Request = original.newBuilder()
                .header("token", token)
                .method(original.method(), original.body())
                .build()
            it.proceed(request)
        })

        okHttpClient.addInterceptor(CacheInterceptor())
        okHttpClient.addInterceptor(BodyInterceptor())

//        if (isDebug) {
//            val loggingInterceptor = HttpLoggingInterceptor()
//            loggingInterceptor.level = HttpLoggingInterceptor.Level.BASIC
//            okHttpClient.addInterceptor(loggingInterceptor)
//        }

        return okHttpClient.build()
    }


    fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {

        return Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl("https://app-api.allinp.top/")
            .addConverterFactory(GsonConverterFactory.create(JSONUtil.createGson()))
            .build()

    }
}